package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.entity.DeviceModel;
import com.wing.dict.model.entity.DictLabel;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.ProductTypeService;
import com.wing.product.service.ProductUnitService;
import com.wing.res.model.response.DeviceOrWorkVo;
import com.wing.sell.model.entity.CustomerProductCatalog;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.sell.model.request.CustomerProductCatalogForm;
import com.wing.sell.model.response.CustomerProductCatalogVO;
import com.wing.sell.service.CustomerProductCatalogService;
import com.wing.sell.service.CustomersInfoService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.CustomerProductCatalogExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ProcessInfoExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 */
@Validated
@Api(value = "Admin-客户产品目录管理", tags = "#/sell/customerProductCatalog")
@RestController("customerProductCatalogController")
@RequestMapping("sell/admin/customerProductCatalog")
@RequiredArgsConstructor
@Slf4j
public class CustomerProductCatalogController {
    //http://production-server-ruizhi/sell/admin/customerProductCatalog/addProduct
    private final CustomerProductCatalogService customerProductCatalogService;

    private final CustomersInfoService customersInfoService;

    private final ProductTypeService productTypeService;
    private final ProductUnitService productUnitService;

    @ApiOperation(value = "查询所有客户产品目录", notes = "搜索")
    @GetMapping("/list")
    public PageResult<CustomerProductCatalogVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "desc") String order,
            Long customerId,
            Long extProductId,
            String cusProductName,
            String cusSkuCode,
            String cusSkuSpec,
            String proTypeId,
            Integer isHaveInSku,
            String notInListIds
    ) {
        Page<CustomerProductCatalogVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }
        
        if (StringUtils.isNotBlank(notInListIds)) {
            params.put("notInListIds",StringUtils.split(notInListIds, ","));
        }
        params.put("isHaveInSku",isHaveInSku);
        params.put("customerId", customerId);
        params.put("cusProductName", cusProductName);
        params.put("extProductId", extProductId);
        params.put("cusSkuCode", cusSkuCode);
        params.put("cusSkuSpec", cusSkuSpec);
        params.put("proTypeId", proTypeId);

        List<CustomersInfo> customersInfos = customersInfoService.list();
        //查询所有的客户
        IPage<CustomerProductCatalogVO> list = customerProductCatalogService.pageList4app(pg, params);
        list.getRecords().stream().forEach(info->{
            info.setCusSkuCode(info.getExtProductCode());
            info.setCusProductName(info.getExtProductName());
            info.setCusProductSpec(info.getExtSpecCode());
            info.setCusProductId(info.getExtProductId());
            if (CollectionUtils.isNotEmpty(customersInfos)){
                customersInfos.forEach(aa->{
                    if (aa.getId().equals(info.getCustomerId())){
                        info.setCustomerName(aa.getCustomerName());
                    }
                });
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加客户产品目录", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CustomerProductCatalogForm.class) CustomerProductCatalogForm customerProductCatalogForm) {
        if (customerProductCatalogService.add(customerProductCatalogForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }
    //1
    @ApiOperation(value = "添加客户产品目录", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addProduct")
    public JsonResult addProduct(@RequestBody CustomerProductCatalogForm customerProductCatalogForm) {
        try {
            customerProductCatalogService.addProduct(customerProductCatalogForm);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }

    }


    @ApiOperation(value = "添加客户产品目录Api", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addProductOutApi")
    public JsonResult addProductOutApi(@RequestBody CustomerProductCatalogForm customerProductCatalogForm) {
        try {
            customerProductCatalogService.addProduct(customerProductCatalogForm);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }

    }


    @ApiOperation(value = "修改客户产品目录", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody CustomerProductCatalogForm customerProductCatalogForm) {
        CustomerProductCatalog customerProductCatalog = customerProductCatalogService.getById(customerProductCatalogForm.getId());
        if (customerProductCatalog == null) {
            return JsonResult.fail("修改失败！");
        }

        if (customerProductCatalogService.updateInfo(customerProductCatalogForm)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除客户产品目录", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerProductCatalogId", value = "客户产品目录id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long customerProductCatalogId) {
        if (customerProductCatalogService.removeById(customerProductCatalogId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "查询客户产品明细", notes = "查询-明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "客户产品目录id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("detail/{id}")
    public JsonResult getDetail(@PathVariable("id") Long id) {
        return JsonResult.success(customerProductCatalogService.getDetail(id));
    }





    @ApiOperation(value = "查询客户产品ID", notes = "查询-明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "客户产品code", required = true, dataType = "String", paramType = "path")
    })
    @GetMapping("getOutProductId/{code}")
    public JsonResult getOutProductId(@PathVariable("code") String code) {
        return JsonResult.success(customerProductCatalogService.getOutProductId(code));
    }


    /**
     * 下载客户产品excel模板
     */
    @ApiOperation(value = "下载客户产品excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 字典数据
        String[] headerArr = {"客户名称(*)", "客户物料编码(*)", "客户物料名称(*)","客户规格码(*)",
                "客户产品类型","产品单位","是否需要包装", "包装说明","是否需要表面处理","表面处理说明"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();

        //客户名称
        List<CustomersInfo> customersInfos = customersInfoService.list();



        if (CollectionUtil.isNotEmpty(customersInfos)) {

            for (CustomersInfo customersInfo : customersInfos) {
                tempStr.append(customersInfo.getCustomerName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("0");
        }

        //客户产品类型
        List<ProductType> productTypes = productTypeService.list();
        if (CollectionUtil.isNotEmpty(productTypes)) {

            for (ProductType yesNodatum : productTypes) {
                tempStr.append(yesNodatum.getName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("4");
        }

        List<ProductUnitInfo> infoList = productUnitService.getUnitDisInfo();
        if (CollectionUtil.isNotEmpty(infoList)) {

            for (ProductUnitInfo unitInfo : infoList) {
                tempStr.append(unitInfo.getName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("5");
        }

        String[] yesNodata = new String[]{"是", "否"};
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("6");

        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("8");

        DownExcelUtil.createExcelTemplate(response, request, "客户目录导入模板", Arrays.asList(headerArr), downData, indexArr);
    }


    /**
     * 导入工序excel
     */
    @ApiOperation(value = "导入客户产品excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            ExcelUtil<CustomerProductCatalogExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<CustomerProductCatalogExcelIn> list = reader.read(is, CustomerProductCatalogExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            customerProductCatalogService.importExcel(list);
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
